package cn.jinjimi.app.main.activity;

import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.AppManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.controller.UserController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.UploadProfileEvent;
import cn.jinjimi.app.custom.event.CustomAreaEvent;
import cn.jinjimi.domain.ServiceManager;
import cn.jinjimi.domain.store.ConfigStore;
import cn.jinjimi.app.entity.Account;
import cn.jinjimi.app.entity.Area;
import cn.jinjimi.app.entity.City;
import cn.jinjimi.app.entity.Province;
import cn.jinjimi.app.main.adapter.CityAdapter;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.Callable;

import bolts.Continuation;
import bolts.Task;

/**
 * Created by haner on 15-1-23.
 */
public class CityActivity extends ToolBarCommonActivity implements AdapterView.OnItemClickListener {

    private ListView mListView;
    private CityAdapter mAdapter;
    private Province mProvince;

    private boolean haveResult;

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_city);
        setTitle(getString(R.string.info_area));
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        mProvince = (Province) getIntent().getSerializableExtra(BundleKey.PARAM_PROVINCE);
        mListView = (ListView) findViewById(R.id.area_city_list);
        mAdapter = new CityAdapter(CityActivity.this);
        mListView.setAdapter(mAdapter);

    }

    protected void initListener() {
        mListView.setOnItemClickListener(this);
    }

    protected void initData() {
        haveResult = getIntent().getBooleanExtra(BundleKey.PARAM_HAVE_AREA_RESULT, false);
        if (mProvince != null) {
            showLoadingIndicator();
            getCityWithProvince(mProvince.id);
        }
    }

    /**
     * 根据省份获取城市信息
     * @param provinceId
     */
    private void getCityWithProvince(final String provinceId) {
        Task.callInBackground(new Callable<Area>() {
            @Override
            public Area call() throws Exception {
                return ServiceManager.getService(ConfigStore.class).fetchCities(provinceId);
            }
        }).continueWith(new Continuation<Area, Void>() {
            @Override
            public Void then(Task<Area> task) throws Exception {
                Area data = task.getResult();
                if (!task.isFaulted() && data != null && data.getCities() != null) {
                    mAdapter.setItems(data.getCities());
                } else if (task.isFaulted()) {
                    ToastUtils.toastMessage(CityActivity.this, R.string.error_bad_network);
                }
                hideLoadingIndicator();
                return null;
            }
        }, Task.UI_THREAD_EXECUTOR);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Account account = AccountManager.getInstance().getAccount();
        City city = mAdapter.getItem(position - mListView.getHeaderViewsCount());

        if (haveResult) {
            EventBus.getDefault().post(new CustomAreaEvent(mProvince, city));
            AppManager.getInstance().finishActivity(AppManager.getInstance().getActivity(AreaActivity.class));
            finish();
            return;
        }

        if (!city.cityName.equals(account.cityName)) {
            UserController.setCity(position - mListView.getHeaderViewsCount(), mProvince, city);
            showLoadingIndicator();
        } else {
            ToastUtils.toastMessage(CityActivity.this, R.string.modify_success);
            AppManager.getInstance().finishActivity(AppManager.getInstance().getActivity(AreaActivity.class));
            finish();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUploadProfileEvent(UploadProfileEvent event) {
        hideLoadingIndicator();
        switch (event.state) {
            case DataEvent.SUCC:
                //show the tip
                ToastUtils.toastMessage(CityActivity.this, getString(R.string.modify_success));
                //此处保存地区信息
                AccountManager.getInstance().updateAccount(AccountManager.NameKey.PROVINCEID, mProvince.id);
                AccountManager.getInstance().updateAccount(AccountManager.NameKey.PROVINCENAME, mProvince.provinceName);
                AccountManager.getInstance().updateAccount(AccountManager.NameKey.CITYID, mAdapter.getItem(event.position).id);
                AccountManager.getInstance().updateAccount(AccountManager.NameKey.CITYNAME, mAdapter.getItem(event.position).cityName);

                //close AreaActivity
                AppManager.getInstance().finishActivity(AppManager.getInstance().getActivity(AreaActivity.class));
                //close self
                finish();
                break;
            case DataEvent.FAIL:
                ToastUtils.toastMessage(CityActivity.this, getString(R.string.error_bad_network));
                break;
        }
    }

}
